package com.bluesmart.mia;

import java.util.ArrayList;
import java.util.List;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.db.chart.model.LineSet;
import com.db.chart.model.Point;
import com.db.chart.view.AxisController.LabelPosition;
import com.db.chart.view.LineChartView;
import com.util.Constant;
import com.util.DensityUtil;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ScheduleActivity extends RelativeLayout implements OnClickListener{
	JSONArray mArray = new JSONArray();

	List<String> mKey = new ArrayList<String>();
	String[] mTime = new String[96];
	String[] mVol = new String[30];
	int mHeight;
	int mScreenWidth;
	int mSelected = 0;
	
	View mSeletedView = null;
	View mView;
	Context mContext;
	
	public ScheduleActivity(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initView();
	}
	
	public ScheduleActivity(Context context, AttributeSet attrs,int arg0) {
		super(context, attrs);
		mContext = context;
		initView();
	}

	public void initView()  {
		LayoutInflater mInflater = LayoutInflater.from(mContext);  
		mView = mInflater.inflate(R.layout.activity_schedule, null); 

		for(int i = 0; i < 96; i++)
		{
			int hour = i/4;
			int min = (i%4)*15;
			
			String hourStr = "" + hour;
			
			if(min == 0) mTime[i] = hourStr + ":0" + min;
			else mTime[i] = hourStr + ":" + min;
		}
        WheelView number = (WheelView)mView.findViewById(R.id.hourpicker);
        number.setViewAdapter(new ArrayWheelAdapter<String>(mContext, mTime,Color.parseColor("#FFFFFF")));
        number.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				WheelView number = (WheelView)mView.findViewById(R.id.minuteicker);
				if(mKey.contains(mTime[newValue]))
				{
					JSONObject item = mArray.getJSONObject(mKey.indexOf(mTime[newValue]));
					number.setCurrentItem(item.getIntValue("goal_ml")/10 - 1);
			        
		        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a29);
					((ImageButton)mView.findViewById(R.id.change)).setSelected(true);
				}
				else
				{
					number.setCurrentItem(0);
			        
		        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a01);
					((ImageButton)mView.findViewById(R.id.change)).setSelected(false);
				}
			}
        });
        
        for(int i = 0; i < 30; i++)
		{
			mVol[i] = String.valueOf(10 + i*10);
		}
        number = (WheelView)mView.findViewById(R.id.minuteicker);
        number.setViewAdapter(new ArrayWheelAdapter<String>(mContext, mVol,Color.parseColor("#FFFFFF")));
        number.addChangingListener(new OnWheelChangedListener(){
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				WheelView number = (WheelView)mView.findViewById(R.id.hourpicker);
				if(mKey.contains(mTime[number.getCurrentItem()]))
				{
					JSONObject item = mArray.getJSONObject(mKey.indexOf(mTime[number.getCurrentItem()]));
					if(mVol[newValue].equals(item.getString("goal_ml")))
		        	{
			        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a29);
						((ImageButton)mView.findViewById(R.id.change)).setSelected(true);
			        }
			        else
			        {
			        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a01);
						((ImageButton)mView.findViewById(R.id.change)).setSelected(false);
			        }
				}
				else
				{
		        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a01);
					((ImageButton)mView.findViewById(R.id.change)).setSelected(false);
		        }
			}
        });

        mView.findViewById(R.id.btn_change).setOnClickListener(this);
		mView.findViewById(R.id.change).setOnClickListener(this);
		
		addView(mView);
	}

	@Override
	public void onClick(View arg0) {
		int index = arg0.getId();
		if(index >= 20000 && index < 21000)
		{
			final LinearLayout layout = (LinearLayout)mView.findViewById(R.id.scrollview);
			
			mSeletedView.setBackgroundColor(Color.parseColor("#0fc0db"));
			mSeletedView = layout.findViewById(10000 + index - 20000);
			mSeletedView.setBackgroundColor(Color.parseColor("#4762a8"));
			
			mSelected = index - 20000;
			

			WheelView number = (WheelView)mView.findViewById(R.id.hourpicker);
			for(int i = 0; i < 96; i++)
			{
				if(mTime[i].equals(mKey.get(mSelected)))
				{
					number.setCurrentItem(i);
					
					number = (WheelView)mView.findViewById(R.id.minuteicker);
					JSONObject item = mArray.getJSONObject(mSelected);
					number.setCurrentItem(item.getIntValue("goal_ml")/10 - 1);
					
		        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a29);
					((ImageButton)mView.findViewById(R.id.change)).setSelected(true);
					
					break;
				}
			}
		
			return;
		}
		
		switch(arg0.getId())
		{
		case R.id.change:
			sendChangeRequest();
			break;

		case R.id.btn_change:
			((MainPageActivity)mContext).changeView(R.id.btn0);
			break;
		}
	}

	private void sendChangeRequest()
	{
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseArray(response).getJSONObject(0);

				if (ruser.getString("resCode").equals("1000")) {
					ToastUtil.showToastWithAlertPic(R.string.success);
					sendHttpRequest(false);
				}
				else if (ruser.getString("resCode").equals("2000")) {
					
				}
				else if (ruser.getString("resCode").equals("3000")) {
					ToastUtil.showToastWithAlertPic(R.string.error_3000);
				}
				else
				{
				}
			}
		};
		

		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("FeedTime", mTime[((WheelView)mView.findViewById(R.id.hourpicker)).getCurrentItem()]);
		params.put("goal_ml", mVol[((WheelView)mView.findViewById(R.id.minuteicker)).getCurrentItem()]);
		
		if(((ImageButton)mView.findViewById(R.id.change)).isSelected())
		{

			if(mArray == null || mArray.size() == 0) return;
			params.put("handType", "delete");
		}
		else
		{
			WheelView number = (WheelView)mView.findViewById(R.id.hourpicker);
			if(mKey.contains(mTime[number.getCurrentItem()]))
			{
				params.put("handType", "update");
			}
			else
			{
				params.put("handType", "add");
			}
		}
		
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/ScheduleHandler.ashx", JSON.toJSONString(params), loginHandler);
	
	}
	
	public void sendHttpRequest(boolean show) {
		mKey.removeAll(mKey);
		mArray = new JSONArray();
		
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, show, false) {
			@Override
			public void onSuccess(String response) {
				if(mHeight == 0)
				{
					mHeight = mView.findViewById(R.id.scrollview).getHeight();
				}
				mArray = JSON.parseArray(response);
				redrawView();
			}
		};
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/ScheduleHandler.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	public void redrawView()
	{
		final LinearLayout layout = (LinearLayout)mView.findViewById(R.id.scrollview);
		layout.removeAllViews();
		
		mSelected = 0;
		
		int count = mArray.size();
		int page = count/8;
		page += count%8==0?0:1;
		
		mScreenWidth = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();

		LayoutInflater mInflater = LayoutInflater.from(mContext);
		
		for(int i = 0; i < page; i++)
		{
			JSONArray chartArray = new JSONArray();
			LineSet lineSet = new LineSet();
			
			View convertView = mInflater.inflate(R.layout.item_schedule, null);
			layout.addView(convertView);
			
			int j = 0;
			for(; j < 8 && 8*i + j < count; j++)
			{
				JSONObject item = mArray.getJSONObject(8*i + j);
				mKey.add(item.getString("FeedTime"));
				
				convertView.findViewById(R.id.schedule0 + 2*j).setVisibility(View.VISIBLE);
				convertView.findViewById(R.id.click0 + j).setVisibility(View.VISIBLE);
				
				((TextView)convertView.findViewById(R.id.schedule0 + 2*j)).setText(item.getString("FeedTime"));
				convertView.findViewById(R.id.schedule0 + 2*j).setOnClickListener(ScheduleActivity.this);
				convertView.findViewById(R.id.click0 + j).setOnClickListener(ScheduleActivity.this);
				
				if(j == 7) convertView.findViewById(R.id.line7).setVisibility(View.VISIBLE);
				else convertView.findViewById(R.id.line0 + 2*j).setVisibility(View.VISIBLE);
				
				if(j == 0)
				{
					if(i == 0) 
					{
						chartArray.add(item);
						mSeletedView = convertView.findViewById(R.id.schedule0);
						mSeletedView.setBackgroundColor(Color.parseColor("#4762a8"));
					}
					else chartArray.add(mArray.getJSONObject(8*i + j - 1));
				}
				chartArray.add(item);

				convertView.findViewById(R.id.schedule0 + 2*j).setId(10000 + 8*i + j);
				convertView.findViewById(R.id.click0 + j).setId(20000 + 8*i + j);
				
				if(i == 0 && j ==0)
				{
					lineSet.addPoint(new Point("", 0));
				}
				else if(i > 0 && j == 0)
				{
					lineSet.addPoint(new Point("", mArray.getJSONObject(8*(i - 1) + 7).getFloatValue("goal_ml")));
				}
				
				lineSet.addPoint(new Point("", item.getFloatValue("goal_ml")));
			}
			
			if(8*i + j < count)
			{
				chartArray.add(mArray.getJSONObject(8*i + j));
			}
			
			if(page == 1) convertView.getLayoutParams().width = mScreenWidth;
			else if(j == 8) convertView.getLayoutParams().width = mScreenWidth;
			else convertView.getLayoutParams().width = (mScreenWidth/8)*(count - 8*i);

			// Style dots
//			lineSet.setDotsColor(Color.RED);
			// Style line
			lineSet.setThickness(DensityUtil.dip2px(mContext, 2));
			lineSet.setColor(Color.parseColor("#fa7597"));
			// Style background fill
			lineSet.setFill(Color.TRANSPARENT);
//			lineSet.setFillColor(Color.RED);
			// Style type
			lineSet.setSmooth(true);
			
			LineChartView chart = (LineChartView)convertView.findViewById(R.id.chart0);
			chart.addData(lineSet);
			chart.setXAxis(false);
			chart.setYAxis(false);
			chart.setYLabels(LabelPosition.NONE);
			chart.setYLabels(LabelPosition.NONE);
			chart.setAxisBorderValues(0, 600, 9);
			chart.show();
 		}
		
		if(mKey.size() > 0)
		{
			WheelView number = (WheelView)mView.findViewById(R.id.hourpicker);
			for(int i = 0; i < 96; i++)
			{
				if(mTime[i].equals(mKey.get(mSelected)))
				{
					number.setCurrentItem(i);
					
					number = (WheelView)mView.findViewById(R.id.minuteicker);
					JSONObject item = mArray.getJSONObject(mSelected);
					number.setCurrentItem(item.getIntValue("goal_ml")/10 - 1);
					
		        	((ImageButton)mView.findViewById(R.id.change)).setImageResource(R.drawable.a29);
					((ImageButton)mView.findViewById(R.id.change)).setSelected(true);
					
					break;
				}
			}
		}
	}
}
